#!/bin/bash
# Script to convert multiple motion files containing different subjects inside from c3d to mmm (only human/subject motion)
#$1 = path to folder with c3d files     		e.g '/common/homes/test/motions/c3d'
#$2 = winter model processor path
#$3 = object model path
#$4 = additional motion names to force convert again separated by ;				TODO
#e.g. bash c3dToMMM.sh ~/.../Recordings/ ~/.../winter_config.xml ~/.../Objects

c3dToMMM()
{
	file=$1
        winter_config=$2
        object_model_path=$3
        forceConvertMotionNames=(${4//;/ })
	filename_base="${file%'.c3d'}" #delete .xml from end of string
        filename="${filename_base}.xml"
        if ! [[ -f $filename ]]; then
		../build/bin/MMMC3DConverter \
			--inputMotion ${file} \
			--outputMotion ${filename}
        fi

        motionNames=($(xmlstarlet sel -t -v "//Motion[not(./Sensors/Sensor[@type='ModelPose']) and ./Sensors/Sensor[@type='MoCapMarker']]/@name" ${filename}) "${forceConvertMotionNames[@]}")
        echo "Non converted motions for $filename: ${motionNames[@]}"
        for ((i=0;i<${#motionNames[@]};i++))
	do
		if [[ ${motionNames[i]} =~ ^(subject)?_?[0-9]{4}$ ]]; then
			../build/bin/MMMMotionConverter \
				--inputMotion $filename     \
				--motionName ${motionNames[i]}                \
				--converterConfigFile "${PWD}"/../data/Model/Winter/NloptConverterVicon2MMM_WinterConfig.xml   \
				--outputModelFile "${PWD}"/../data/Model/Winter/mmm.xml                           \
				--outputModelProcessorConfigFile ${winter_config}                                 \
				--outputMotion $filename
		elif ! [-z "$3" ]; then
			directoryPath=${object_model_path}/${motionNames[i]}
			if [ -d $directoryPath ]; then
				configFile=$(find $directoryPath -name 'NloptConverterVicon2MMM_*.xml')
		                modelFilePath=$(find $directoryPath -name "${motionNames[i]}.xml")
				if [ -z "$configFile" ]; then
					echo "\Could not find config file in $directoryPath"
				elif [ -z "$modelFilePath" ]; then
					echo "\Could not find model file in $directoryPath"
				else
					../build/bin/MMMMotionConverter \
						--inputMotion $filename     \
						--motionName ${motionNames[i]}                \
						--converterConfigFile ${configFile}   \
						--outputModelFile ${modelFilePath}                          \                                      \
						--outputMotion $filename
				fi
			else
				echo "$directoryPath does not exist"
			fi
		fi
	done
}
export -f c3dToMMM

if ! [ -d "$1" ]; then
        echo "Error in required argument 1: $1 is no valid directory!"
	exit
fi
arg1="$1"
if ! [ -f "$2" ]; then
        echo "Error in required argument 2: $2 is no valid file!"
	exit
fi
arg2="$2"
if [[! -z "$3" ]] && [[ ! -d "$3" ]]; then
        echo "Error in required argument 3: $3 is no valid directory!"
	exit
fi
arg3="$3"
arg4="$4"
find $1 -name *.c3d -type f | xargs -I% -P8 bash -c "c3dToMMM \"%\" \"$arg2\" \"$arg3\"  \"$arg4\" "
exit
